import MySQLdb
import time
from BApiFans import get_fan_fan
import BApiFans as api
import csv


def n2t(time_num):
    timeArray = time.localtime(time_num)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    return otherStyleTime


def tos(obj):
    return '\"' + obj + '\"'


def json_to_list(fan_list, pid):
    print('>> 正在将JSON转化为可导入CSV的列表,fan_list长度为：', len(fan_list))
    zone_list = []
    for bfan in fan_list:
        this_line = [bfan['mid'], tos(n2t(bfan.get('mtime'))), tos(bfan['uname']), tos(
            bfan['face']), tos(bfan['sign']), None, pid, tos(n2t(time.time())), 0]
        zone_list.append(this_line)
    return zone_list


def update_fan_fans():
    db = MySQLdb.connect("localhost", "root", "root",
                         "gal_birthday", charset='utf8')
    cursor = db.cursor()
    sql = ''
    fanlist = json_to_list()

    print(">> 待更新数据:", len(fanlist))
    api_count = 1
    for fan in fanlist:
        if api_count % 20 == 0:
            print('>> 已爬取 %s 条数据，进度 %2.2f%s ，休息 1 S…' %
                  (api_count, api_count / len(fanlist) * 100, '%'))
            time.sleep(1)
        api_count += 1
        # mid 第0个
        fans_num = get_fan_fan(fan[0])
        print('>> uname : %s fans : %s' % (fan[2], fans_num[5]))


def display_to_csv(csvlist,pid):
    print('正在写入...')
    with open("./%s-bilibili-fans.csv"%pid, "w", encoding='UTF-8-sig', newline='') as csvfile:
        writer = csv.writer(csvfile)
        # 先写入columns_name
        writer.writerow(["UID", "关注时间", "用户名", "头像", "签名",
                        "粉丝数", "PID", "更新时间", "删除标识"])
        # 写入多行用writerows
        writer.writerows(csvlist)
        csvfile.close
    print('写入完成！')


def get_CSV(SESSDATA, pid):
    try:
        fanlist = api.get_fan_list(SESSDATA, pid)
        csvlist = json_to_list(fanlist, pid)
        display_to_csv(csvlist,pid)
        return len(csvlist)
    except Exception as ex:
        print(ex)
        print(">> 导出失败")
        return -1


def get_CSV_fan(SESSDATA, pid):
    try:
        fanlist = api.get_fan_list(SESSDATA, pid)
        csvlist = json_to_list(fanlist, pid)
        api_count = 1
        for item in csvlist:
            if api_count % 20 == 0:
                print('>> 已获取 %s 条数据，进度 %2.2f%s ，休息 1 S...' %
                      (api_count, api_count / len(fanlist) * 100, '%'))
                time.sleep(1)
            api_count += 1
            item[5] = get_fan_fan(item[0])
            print('>> ', item)
        display_to_csv(csvlist,pid)
        return len(csvlist)
    except Exception as ex:
        print(ex)
        print(">> 导出失败")
        return -1